<?php
/**
 *  * 历史数据的处理
 *   * 更新所有员工的考勤状态，根据打卡记录生成，排除不是上海和销售部
 *   */
apf_require_class('Oa_Job_Attendance_Abstract');
apf_require_class("Tools_Tools");
apf_require_class('Const_LeaveType');
apf_require_class('Bll_Attendance_DailyReport');
apf_require_class('Bll_Attendance_DailyLeave');
apf_require_class('Bll_Attendance_AccessDayRecord');
class Oa_Job_Attendance_SetUserCardStatus extends Oa_Job_Attendance_Abstract {

    private $writedb = "attendance_master";
    private $all_uesr = array();

    public function run($params){
        $start = $params['start'];
        $end = $params['end'];
        $in_uid=empty($params['uid']) ? 0 : intval($params['uid']);
        if(empty($start) || empty($end)){
            $this->log('必须设置起始时间');exit;
        }
        $all_user = $this->get_all_user_info($in_uid);

        $startx= strtotime($start);
        $endx = strtotime($end);

        $holiday_country = Tools_Tools::get_instance()->each_year_holiday_country();
        $no_work_day = Tools_Tools::get_instance()->holiday_country();
        $holiday_country=array_merge($holiday_country,$no_work_day);
        $special_work_day = Tools_Tools::get_instance()->special_work_day();

        $i=$startx;
        while(true){
            if($i > $endx){
                break;
            }
            $day = date('Ymd',$i);//一天是2000条
            $day_t = date('Y-m-d',$i);
            $weekday = date('w',$i);
            $i+=86400;
            //过滤节假日
            if(in_array($day_t,$holiday_country)){
                continue;
            }
            if(($weekday == 0 || $weekday == 6) && !in_array($day_t,$special_work_day)) {//是周6日，但不是特殊工作日，0929
                continue;
            }

            $sql = "SELECT * FROM access_day_record WHERE access_date={$day}";
            $tmp = $this->get_db_rows($sql,$this->writedb,array());
            if(empty($tmp)){
                $this->log("Not Found 读取指定所有打卡记录....");continue;
            }
            $user_access = array();
            foreach($tmp as $val){
                $user_access[$val['user_id']]=$val;
            }
            foreach($all_user as $uid=>$user){
                $is_later=$leave_early=0;
                if(isset($user_access[$uid])){
                    $status = $this->check_day_work_status($day,$user_access[$uid]['start_work'],$user_access[$uid]['end_work']);
                    if($status[0]==5 && $status[0]==6){
                        continue;
                    }
                    $am_status=$status[0];
                    $pm_status=$status[1];
                    if($status[0]==1){
                        $is_later=1;
                    }
                    if($status[1]==2){
                        $leave_early=1;
                    }
                }else{//没有打卡记录的记为缺勤
                    $am_status=3;
                    $pm_status=4;
                }
                $sql = "UPDATE user_day_status SET am_status={$am_status},pm_status={$pm_status},is_later=$is_later ,leave_early=$leave_early WHERE user_id = {$uid} AND dateline = {$day}";
                $this->execute($sql,array(),$this->writedb);
            }
            $this->log($day."记录 Done....");
        }
        $this->log("修改完成");
    }

    private function get_all_user_info($uid=0) {
        $result = array();
        $sale_department = APF::get_instance()->get_config('sale_department');
        //开通打卡机的城市
        $city_card = APF::get_instance()->get_config('city_card');
        $city_names = array_values($city_card);
        $city = " AND city_name IN('".implode("','", $city_names)."')";

        if($uid){
            $sql = "SELECT * FROM user_info WHERE user_id = {$uid}  {$city} ";
            $userinfo = $this->get_db_row($sql,$this->writedb);
            if(empty($userinfo['department_name'])){
                return $result;
            }
            if(!empty($sale_department[$userinfo['department_id']])){
                return $result;
            }
            return array($uid=>$userinfo);
        }

        $start = 0;
        $limit = 100;
        while(true) {
            $sql = "SELECT * FROM user_info WHERE user_id > {$start}  {$city} ORDER BY user_id asc limit {$limit}";
            $tmp = $this->get_db_rows($sql,$this->writedb,array());
            if(empty($tmp)) {
                $this->log("取完所有用户数据!");
                break;
            }
            $count = count($tmp);
            $start = $tmp[$count - 1]['user_id'];
            $result = array_merge($result,$tmp);
        }
        $last=array();

        foreach($result as $k=>$val){//不用管销售部
            if(!empty($sale_department[$val['department_id']])){
                unset($result[$k]);
                continue;
            }
            $last[$val['user_id']] = $val;
        }
        return $last;
    }
    //临时使用
    /**
    * 检测当前的打卡记录
    * @param int $day 20120901
    * @param int $start_work 第一次打卡时间 0910
    * @param int $end_work 最后一次打卡时间 1805
    * @param int $deconfig 读取那份配置
    */
    public function check_day_work_status($day,$start_work,$end_work,$deconfig=0){
        $checklist = array(
                'am'=>array(
                        0=>array('start'=>0,'end'=>911,'status'=>5),//正常
                        1=>array('start'=>910,'end'=>931,'status'=>1)//迟到
                ),
                'pm'=>array(
                        0=>array('start'=>1759,'end'=>2359,'status'=>6), //正常
                        1=>array('start'=>1729,'end'=>1800,'status'=>2),//早退
                ),
                'am_q'=>3,//上午缺勤
                'pm_q'=>4//下午缺勤
        );
        $status = array(
                0=>$checklist['am_q'],
                1=>$checklist['pm_q']
        );
        if(empty($start_work) && empty($end_work)){
            return $status;
        }
        //apf_require_class("Bll_Attendance_SpecialDay");
        //$spday_bll = new Bll_Attendance_SpecialDay();
        //$speciday = $spday_bll->get_special_day($day);
        if($day==20120929){
            $speciday=array(
                    'start_time'=>900,
                    'end_time'=>1600,
                    'status'=>1
            );
        }
        //特殊工作日,上下行时间不是9-18
        if(!empty($speciday) && $speciday['status']==1){
            if($speciday['start_time']==900){
                foreach($checklist['am'] as $val){//上午考勤状态
                    if($start_work < $val['end'] && $start_work > $val['start']){
                        $status[0]=$val['status'];
                        break;
                    }
                }
            }else{
                if($start_work <= $speciday['start_time']){
                    $status[0]=5;
                }
            }
            if($end_work >= $speciday['end_time']){
                $status[1]=6;
            }
            return $status;
        }
        foreach($checklist['am'] as $val){//上午考勤状态
            if($start_work < $val['end'] && $start_work > $val['start']){
                $status[0]=$val['status'];
                break;
            }
        }
        if($start_work > 1800){
            return $status;
        }
        foreach($checklist['pm'] as $val){//下午考勤状态
            if($end_work > $val['start'] && $end_work < $val['end']){
                $status[1]=$val['status'];
                break;
            }
            if($status[1]==2 && $start_work>1430){
                $status[1]=$checklist['pm_q'];
            }
        }
        return $status;
    }
}